#include <mymuduo/TcpServer.h>
#include <string>
#include <mymuduo/log.h>
#include <functional>
class EchoServer
{
public:
    EchoServer(EventLoop *loop, const InetAddress &listenAddr, const std::string &name) : server_(loop, listenAddr, name), loop_(loop)
    {
        // 注册回调函数
        server_.setConnectionCAllback(std::bind(&EchoServer::onConnection, this, std::placeholders::_1));

        server_.setMessageCallback(std::bind(&EchoServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 设置合适的loop线程数量

        server_.setThreadNum(3);
    }
    void start(){
        server_.start();
    }

private:
    // 建立连接或断开连接的回调
    void onConnection(const TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            LOG_INFO("Connection Up: %s\n", conn->peerAddr().toIpPort().c_str());
        }
        else
        {
            LOG_INFO("Connection Down: %s\n",conn->peerAddr().toIpPort().c_str());
        }
    }

    // 可读写事件回调
    void onMessage(const TcpConnectionPtr &conn, Buffer *buf, TimeStamp Time)
    {
        std::string msg = buf->retrieveAllAsString();
        conn->send(msg);
        conn->shutdown(); // 这里关闭写端EPOLLHUB=>closeCallback
    }
    EventLoop *loop_; // baseloop
    TcpServer server_;
};

int main()
{
    EventLoop loop;
    InetAddress addr(8000);
    EchoServer server(&loop, addr, "EchoServer_01");
    server.start();
    loop.loop();//启动mainloop

    return 0;
}